package com.ljc.db.transport;

/**
 * Packager 则是 Encoder 和 Transporter 的结合体，直接对外提供 send 和 receive 方法
 */
public class Packager {
    private Transporter transporter;
    private Encoder encoder;

    public Packager(Transporter transpoter, Encoder encoder) {
        this.transporter = transpoter;
        this.encoder = encoder;
    }

    /**
     * 数据发送方法：encoder编码后通过transporter发送
     */
    public void send(Package pkg) throws Exception {
        byte[] data = encoder.encode(pkg);
        transporter.send(data);
    }

    /**
     * 数据接收方法：transporter接收后通过encoder解码
     */
    public Package receive() throws Exception {
        byte[] data = transporter.receive();
        return encoder.decode(data);
    }

    public void close() throws Exception {
        transporter.close();
    }
}
